const app = getApp()
const publicFun = require('/utils/public.js')
import { getAuthCode, getAuthCodeLogin } from '/utils/request'
Page({
  data: {
    protocolStatus: 1, //是否同意协议：1 同意 0 不同意
    authCode: '',
    loginType: null,
  },
  onLoad() {
    this.setData({
      systemInfo: app.globalData.systemInfo
    })
    my.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
  },
  authTap() {
    if(this.data.protocolStatus === 1){
      this.setData({protocolStatus: 0})
    }else{
      this.setData({protocolStatus: 1})
    }
  },
  onGetAuthorize(res) { //授权
    this.getAuthorize();
    this.setData({loginType: 0});
  },
  onGetAuthorizeMobile(res) { //手机号登录/注册
    this.getAuthorize();
    this.setData({loginType: 1});
  },
  onAuthError(res) { //授权失败
    publicFun.showToast('授权失败');
  },
  getAuthorize() {
    let that = this;
    if(this.data.protocolStatus == 1){
      my.showLoading();
      my.getAuthCode({
        scopes: ['auth_base'],
        success: (res) => {
          if(res.authCode){
            that.setData({
              authCode: res.authCode
            });
            my.getOpenUserInfo({
              success: (ress) => {
                // 以下方的报文格式解析两层 response
                let userInfo = JSON.parse(ress.response).response; 
                app.globalData.userInfo = userInfo;
                if(app.globalData.userInfo || userInfo){
                  if(app.globalData.secondCount){
                    that.LoginTap();
                  }else{
                    app.getSecondCount().then(res => {
                      that.LoginTap();
                    });
                  }
                }else{
                  publicFun.showToast('用户信息获取，请重新授权');
                }
              },
              fail: (resss) => {
                publicFun.showToast('用户信息获取，请重新授权');
              },
            });
          }
        },
        fail: (err) => {
          publicFun.showToast(err.message);
        }
      });
    }else{
      publicFun.showToast("请勾选蔚蓝地图协议")
    }
  },
  LoginTap() {
    if(this.data.loginType == 0) {
      this.LoginAuth();
    }else{
      this.LoginQuick();
    }
  },
  async LoginAuth() {
    try{
      let name = app.globalData.userInfo.nickName ? app.globalData.userInfo.nickName : '蔚蓝';
      let params = {
        zhifubaoCode: this.data.authCode,
        Token: '支付宝气候行动小程序',
        Type: app.globalData.mobileInfo,
        source: 3, // 1 蔚蓝日历 2 随手拍 3 气候行动
        NickName: name,
        HeadImg: app.globalData.userInfo.avatar ? app.globalData.userInfo.avatar : '',
        Sex: app.globalData.userInfo.gender === "m" ? 1 : 2,
      }
      const res = await getAuthCodeLogin(params)
      if(res.S == 1){
        my.hideLoading();
        if(res.isneedphone == 0){
          publicFun.showToast(res.M, 2000);
          app.globalData.userid = res.R;
          app.globalData.zfbUid = res.ZFBUserId;
          app.globalData.usermiyao = res.usermiyao;
          my.setStorage({
            key: 'userid',
            data: res.R
          }); 
          my.setStorage({
            key: 'usermiyao',
            data: res.usermiyao
          }); 
          my.setStorage({
            key: 'zfbUid',
            data: res.ZFBUserId
          });
          my.switchTab({
            url: '/pages/index/index'
          });
          
          app.getUserData();
          app.getAqiDetail();
        }else{
          my.navigateTo({
            url: '/pages/loginBind/loginBind?userid='+res.R
          });
        }
      }else{
        my.hideLoading();
        publicFun.showToast(res.M ? res.M : '加载失败');
      }
    }catch(e) {
      publicFun.showToast('失败，请稍后再试')
    }
  },
  async LoginQuick() {
    try{
      let params = {
        authorization_code: "authorization_code",
        zhifubaoCode: this.data.authCode,
        refreshtoken: "",
      }
      const res = await getAuthCode(params)
      if(res.S == 1){
        my.hideLoading();
        app.globalData.zfbUid = res.UserInfo.user_id;
        my.setStorage({
          key: 'zfbUid',
          data: res.UserInfo.user_id
        });
        my.navigateTo({
          url: '/pages/loginQuick/loginQuick'
        });
      }else{
        my.hideLoading();
        publicFun.showToast(res.M ? res.M : '加载失败');
      }
    }catch(e) {
      publicFun.showToast('失败，请稍后再试')
    }
  },
  blueMapTap() { //协议
    my.navigateTo({
      url: '/pages/blueMap/blueMap'
    });
  },
});
